package com.chhuang.huaao.thread;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;

import com.chhuang.core.holder.SpringContextHolder;
import com.chhuang.huaao.handler.ServerHandler;
import com.chhuang.huaao.po.HaMachine;
import com.chhuang.huaao.service.IHaMachineService;
import com.chhuang.system.consts.SysConstants;
import com.chhuang.utils.config.SysConfig;

/**
 * 当用户查看某个设备时，打开这个线程，请求设备信息
 * @author CHHUANG
 *
 */
public class MachineStatusFlushThread implements Runnable {
	private static final Log log = LogFactory.getLog(MachineStatusFlushThread.class);

	private IHaMachineService machineService = SpringContextHolder.getBean("haMachineServiceImpl");
	
	private HaMachine machine;
	
	public MachineStatusFlushThread(HaMachine machine){
		this.machine = machine;
	}

	@Override
	public void run() {
		IoSession session = ServerHandler.sessionMap.get(machine.getMachineNum());
		long now = System.currentTimeMillis();
		long hearttime = machine.getHeartTime()==null ? now : machine.getHeartTime().getTime();
		hearttime = now - hearttime;
		long max = SysConfig.getLong(SysConstants.Config.MAX_HEART_TIME, 303000l);
		if(session!=null && !session.isClosing() && session.isConnected() && hearttime<=max){//在线
			int intArray[] = new int[5];
			//校验位
			intArray[0] = Integer.parseInt("f5", 16);
			
			//序列号
			String id = Integer.toHexString(Integer.parseInt(machine.getMachineNum()));
			int len;
			if(id.length()<4){//补全0
				len = id.length();
				for(int i=0;i<4-len;i++){
					id = "0"+id;
				}
			}
			log.debug(machine.getMachineNum()+" ---> "+id);
			intArray[1] = Integer.parseInt(id.substring(0, 2),16);
			intArray[2] = Integer.parseInt(id.substring(2, 4),16);
			
			//有效数据长度
			intArray[3] = 1;
			
			//发送查询命令
			intArray[4] = Integer.parseInt("AA", 16);
			
			String hexStr = "";
			byte command[] =  new byte[5];
			for(int i=0; i<intArray.length; i++){
				hexStr += Integer.toHexString(intArray[i])+" ";
				if(intArray[i] > 127){
					command[i] = (byte) (intArray[i]-256);
				}else{
					command[i] = (byte) intArray[i];
				}
			}
//			String command = ServerHandler.ORDERS[1];
			log.debug("服务器发送16进制命令："+hexStr);
			
			session.write(IoBuffer.wrap(command));
			//启动线程等待设备回复
			long time = machine.getHeartTime()==null? 0 : machine.getHeartTime().getTime();
			new Thread(new WaitThread(machine.getMachineId(), time)).start();
			
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			session.write(IoBuffer.wrap(command));
			
		}else{//离线
			if(session!=null){
				session.close(true);session=null;
			}
			//修改数据库在线状态
			machine.setMachineOnlineStatus(0);
			machine.setModifyTime(new Date());
			try {
				machineService.update(machine);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			//修改sessionMap
			ServerHandler.sessionMap.remove(machine.getMachineNum());
		}
		
	}
	
//	public static void main(String[] args) {
//		int a = 100;
//		System.out.println((byte)(a & 0xff));
//	}
}
